package com.zhuangjie.rabbit.listen.wrap;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.UUID;

@Configuration
@Slf4j
public class MQAutoConfigListener  {
    @Autowired
    private ConnectionFactory connectionFactory;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired(required = false)
    private List<MQListener> mqListeners;


    /**
     * 自动配置mq的监听器，处理声明的监听
     */
    @PostConstruct
    public void autoConfigMQ() {
        log.info("MQ“监听”自动配置中...");
        if (mqListeners == null ) return;
        for (MQListener mqListener : mqListeners) {
            String queueName = mqListener.listenQueue();
            SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
            // 设置手动消费成功确认，如果不设置，然后你在代码中又手动确认，会出现重复确认报错
            container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
            container.setQueues(new Queue(queueName));
            container.setMessageListener(mqListener);
            registerBean(genListenerName(),container);
        }
    }
    private void registerBean(String beanName,Object bean) {
        // 将实例手动注册到IOC容器中
        ConfigurableListableBeanFactory beanFactory =
                ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
        beanFactory.registerSingleton(beanName, bean);
    }
    private String genListenerName() {
        return "MQListener:"+ UUID.randomUUID();
    }
}
